#include<iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include "Comm.hpp"
#include <cstring>
#include <unistd.h>

void Usage(const char* proc)
{
    std::cout << "Usage:\n\t" << proc << " server_ip server_port" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(Usage_Err);
    }
    
    //1.socket
    int Socket = socket(AF_INET, SOCK_STREAM,0);
    if(Socket < 0)
    {
        std::cout << "socket failure" << std::endl;
        exit(Socket_Err);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    inet_pton(AF_INET,server_ip.c_str(),&server.sin_addr);

    int n = connect(Socket,CONV(&server),sizeof(server));
    if( n != 0)
    {
        std::cout << "connect faulure" << std::endl;
    }
    std::cout << "connect success" << std::endl;

    while(true)
    {
        std::string message;
        std::cout << "client Enter#:";
        getline(std::cin,message);
        int n = write(Socket,message.c_str(),message.size());
        if(n > 0)
        {
            char buffer[1024];
            read(Socket,buffer,sizeof(buffer));
            std::cout << buffer << std::endl;
        }
        else
        {
            std::cout << "write failure" << std::endl;
        }
    }

    return 0;
}